package service

import (
	"gf/library/jwt"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"net/http"
)

// 中间件管理服务
var Middleware = middlewareService{}

type middlewareService struct{}

// 允许接口跨域请求
func (s *middlewareService) CORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}

// 自定义上下文对象
func (s *middlewareService) Ctx(r *ghttp.Request) {

	// 执行下一步请求逻辑
	r.Middleware.Next()
}

// 登录授权
func (s *middlewareService) Auth(r *ghttp.Request) {
	header := r.Header

	token := ""
	var userToken = header["User-Token"]
	for _, n := range userToken {
		token = gconv.String(n)
	}

	if token == "" {
		r.Response.WriteStatus(http.StatusForbidden)
		return
	}

	parseToken, err := jwt.ParseToken(token, jwt.Secret)
	if err != nil {
		r.Response.WriteStatus(http.StatusForbidden)
		return
	}

	//g.Dump(parseToken)

	r.SetCtxVar("uid", parseToken)

	r.Middleware.Next()
}
